//cnpm install moment --save 格式化时间
const moment = require("moment");
// 引入数据库的模块
const { connection, requestQuery } = require("../database/db");
//cnpm install bcryptjs --save  加密模块
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
// 生成图片验证码
const svgCaptcha = require('svg-captcha')
// 引入token模块
const JWT = require("../utils/token")
//随机生成字符串cnpm i string-random --save
const stringRandom = require('string-random');

// 1.定义个临时的图片验证码
var temcaptcha = null
// 2.定义一个临时的短信验证码
var tempcode = null
//3、定义一个临时的手机号
var tempphone = null

//用户列表
exports.UserList = async (req, res) => {
    //get传值通过req.query  {page:1,size:10}
    console.log(req.query);
    let page = req.query.page || 1
    let size = req.query.size || 10
    let sort = req.query.sort || "ASC"
    let index = (page - 1) * size

    //countSql 查询可用用户总数
    let countSql = `SELECT COUNT(*) FROM users WHERE is_show=1`
    let countResult = await requestQuery(countSql)
    let total = countResult[0]['COUNT(*)']

    //列表sql
    let userSql = `SELECT * FROM users WHERE is_show=1 ORDER BY sort ${sort} LIMIT ${index},${size}`
    //用户列表
    let userListData = await requestQuery(userSql)
    //找到总页数
    let totalPage = Math.ceil(total / size)

    res.json({
        status: 200,
        total: total,
        page: page,
        size: size,
        sort: sort,
        totalpage: totalPage,
        data: userListData
    })
}
// 用户注册
// post body
exports.UserRegister = (req, res) => {
    console.log(req.body);  //{user_name:"admin",user_password:"123456"}
    let user_name = req.body.user_name
    let user_password = req.body.user_password
    let phone = req.body.phone

    //格式化时间 2021-03-20 09:29:20
    let nowTime = moment().format("YYYY-MM-DD HH:mm:ss")

    //用户和手机号不能重复添加
    //先查询用户名是否存在
    let user_name_sql = `SELECT user_name from users WHERE user_name=? AND is_show=1`
    connection.query(user_name_sql, user_name, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "用户注册失败1",
                status: 1001,
                data: err
            })
        }
        console.log(result_name);  //得到一个数组
        //如果result_name是一个空数组，说明该用户名可用
        if (result_name == "") {
            //如果条件成立，说明该用户名可用
            //再判断手机号是否存在
            let phone_sql = `SELECT phone from users WHERE phone=? AND is_show=1`
            connection.query(phone_sql, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "用户注册失败2",
                        status: 1002,
                        data: err
                    })
                }
                if (result_phone == "") {
                    //如果条件成立说明手机号可用
                    //用户名也是可用的，可以写入数据库了
                    let register_sql = `INSERT INTO users SET user_name=?,user_password=?,phone=?,is_show=1,create_time="${nowTime}"`
                    //hashPassword对密码进行加密
                    let hashPassword = bcrypt.hashSync(user_password, salt);
                    connection.query(register_sql, [user_name, hashPassword, phone], (err, data) => {
                        if (err) {
                            return res.json({
                                msg: "用户注册失败3",
                                status: 1003,
                                data: err
                            })
                        }
                        console.log(data);
                        if (data.affectedRows == 1) {
                            return res.json({
                                msg: "恭喜您注册成功，可以放心购物了",
                                status: 200,
                                data: data
                            })
                        } else {
                            return res.json({
                                msg: "用户注册失败4",
                                status: 1004,
                                data: err
                            })
                        }

                    })
                } else {
                    return res.json({
                        msg: "该手机号存在，请换个手机号重新注册",
                        status: 1005
                    })
                }
            })
        } else {
            //说明用户名不可用
            return res.json({
                msg: "该用户名存在，请换个用户名重新注册",
                status: 1006
            })
        }

    })
}

// 用户登录
// http://localhost:3000/user/login
exports.Login = (req, res) => {
    let user_name = req.body.user_name
    let user_password = req.body.user_password
    //先查询用户名是否存在
    let user_name_sql = `SELECT user_name,user_password from users WHERE user_name=? AND is_show=1`
    connection.query(user_name_sql, [user_name], (err, data) => {
        if (err) {
            return res.json({
                msg: "数据库查询失败",
                status: 5001,
                data: err
            })
        }
        if (data.length == 0) {
            //如果条件成立说明用户名不存在
            return res.json({
                msg: "该用户不存在，请注册用户名",
                status: 404
            })
        } else {
            console.log(data); //[{user_name:"xxx",user_password:"xxx"}]
            //data[0].user_password 数据库中查询出来的密码
            let check_user_password = bcrypt.compareSync(req.body.user_password, data[0].user_password);
            //check_user_password==true密码一致
            console.log(check_user_password);
            if (!check_user_password) {
                return res.json({
                    msg: "密码错误，请重新输入密码",
                    status: 404
                })
            } else {
                let token = JWT.createToken({
                    user_name: user_name,
                    isLogin: true
                })

                JWT.checkToken(token).then(result => {
                    console.log(1111);
                    console.log(result);
                    console.log(2222);
                })
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    token: token,
                    data: data
                })
            }
        }
    })

}


//  图片验证码captcha
exports.SvgCaptcha = (req, res) => {
    var captcha = svgCaptcha.create({
        size: 4,
        ignoreChars: '0o1i',
        noise: 2,
        color: true,
        background: '#fff'
    });
    res.type('svg');
    tempcaptcha = captcha.text.toLowerCase()
    res.status(200).send(captcha.data);
    console.log(captcha.text);
}

// 短信验证码
exports.MessageCode = (req, res) => {
    //第一步：输入正确的手机号
    //第二步：点击获取验证码，发起请求
    //第三步：发送短息的内容+随机的验证码
    // req.body {phone:"13673618137"}
    let codeStr = ("000000" + Math.floor(Math.random() * 999999)).slice(-6)
    tempphone = req.body.phone
    tempcode = codeStr
    console.log(tempcode);
    res.json({
        msg: "发送成功",
        status: 200,
        code: codeStr
    })

}

// 短信登录接口
exports.PhoneLogin = async (req, res) => {
    //post来提交数据
    //req.body  {phone:"13673618137","captcha":"abcd",code:"123456"}
    //在该接口中要验证短信验证码和图片验证码
    console.log(tempcaptcha);
    console.log(tempcode);
    console.log(tempphone);
    //获取用户提交的数据
    let phone = req.body.phone
    let code = req.body.code
    let captcha = req.body.captcha

    if (tempcaptcha != captcha) {
        return res.json({
            msg: "图片验证码不正确",
            status: 1001
        })
    } else if (tempcode != code) {
        return res.json({
            msg: "短信验证码不正确",
            status: 1002
        })
    } else if (tempphone != phone) {
        return res.json({
            msg: "手机号不正确",
            status: 1003
        })
    } else {
        //到这来说明上边条件都成立了
        //判断手机号是否存在
        //1、手机号不存在，将该手机号注册到数据库
        let phone_sql = `SELECT * from users WHERE phone=? AND is_show=1`
        let phone_result = await requestQuery(phone_sql, phone)
        if (phone_result.length == 0) {
            //如果条件成立说明手机号不存在，需要将手机号注册到数据库
            let user_name = "hg_" + stringRandom(10) + new Date().getTime()
            let nowTime = moment().format("YYYY-MM-DD HH:mm:ss")
            let userSql = `INSERT INTO users (user_name,phone,is_show,create_time) VALUES ("${user_name}","${phone}","1","${nowTime}")`
            let result = await requestQuery(userSql)
            if (result.affectedRows == 1) {
                return res.json({
                    msg: "登录成功",
                    status: 200,
                    data: result
                })
            } else {
                return res.json({
                    msg: "服务器错误",
                    status: 5001
                })
            }
        } else {
            //2、手机号存在，直接登录即可
            return res.json({
                msg: "登录成功",
                status: 200,
                data: phone_result
            })
        }
    }

}
